//index.js
//获取应用实例

const app = getApp();
const GoEasy = require('../../utils/goeasy-1.0.11');

Page({
    data: {
        goeasy: null,
        messages: [],
        message: ""
    },
    onLoad: function () {
        this.initGoEasy();
        this.subscribeMessage();
    },
    initGoEasy() {//初始化goeasy
        var self = this;
        this.goeasy = GoEasy({
            host: 'hangzhou.goeasy.io',
            appkey: "您的appkey",
            onConnected: function () {
                console.log("GoEasy connect successfully.");
                self.unshiftMessage("连接成功.");
            },
            onDisconnected: function () {
                console.log("GoEasy disconnected.")
                self.unshiftMessage("连接已断开.");
            },
            onConnectFailed: function (error) {
                console.log(error);
                self.unshiftMessage("连接失败，请检查您的appkey和host配置");
            }
        })
    },

    unshiftMessage(content) {
        var formattedTime = new Date().formatDate("hh:mm");
        var message = formattedTime +" "+ content;
        var messages = this.data.messages;
        messages.unshift(message);
        this.setData({
            messages: messages
        })
    },


    subscribeMessage() {//订阅消息
        var self = this;
        this.goeasy.subscribe({
            channel: "my_channel",
            onMessage: function (message) {
                self.unshiftMessage(message.content);
            },
            onSuccess: function () {
                self.unshiftMessage('订阅成功.');
            }
        });
    },

    sendMessage: function () {//发送消息
        var self = this;
        var content = this.data.message;
        if (content.trim() != '') {
            this.goeasy.publish({
                channel: "my_channel",
                message: self.data.message,
                onSuccess: function () {
                    self.setData({
                        message: ''
                    }); //清空发送消息内容
                    console.log("send message success");
                },
                onFailed: function (error) {
                    self.unshiftMessage('发送失败，请检查您的appkey和host配置.');
                }
            });
        }
    }
})
